<template>
  <ElForm ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <ElFormItem prop="tenantId">
      <ElInput v-model="loginForm.tenantId" placeholder="租户">
        <template #prefix>
          <ElIcon class="el-input__icon">
            <Discount />
          </ElIcon>
        </template>
      </ElInput>
    </ElFormItem>
    <ElFormItem prop="userName">
      <ElInput v-model="loginForm.userName" placeholder="用户名">
        <template #prefix>
          <ElIcon class="el-input__icon">
            <user />
          </ElIcon>
        </template>
      </ElInput>
    </ElFormItem>
    <ElFormItem prop="password">
      <ElInput v-model="loginForm.password" type="password" placeholder="密码" show-password autocomplete="new-password">
        <template #prefix>
          <ElIcon class="el-input__icon">
            <lock />
          </ElIcon>
        </template>
      </ElInput>
    </ElFormItem>
    <ElRow v-if="resCode.captchaEnabled" :gutter="10">
      <ElCol :span="16">
        <ElFormItem prop="code">
          <ElInput v-model="loginForm.code" placeholder="验证码">
            <template #prefix>
              <ElIcon class="el-input__icon">
                <CircleCheck />
              </ElIcon>
            </template>
          </ElInput>
        </ElFormItem>
      </ElCol>
      <ElCol :span="8">
        <ElFormItem>
          <img :src="resCode.img" @click="getCode" class="login-code-img" />
        </ElFormItem>
      </ElCol>
    </ElRow>
  </ElForm>
  <div class="login-btn">
    <ElButton :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置</ElButton>
    <ElButton :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      登录
    </ElButton>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElForm, ElFormItem, ElInput, ElRow, ElCol, ElIcon, ElButton, ElNotification } from "element-plus";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { codeApi, loginApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import md5 from "md5";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  tenantId: import.meta.env.VITE_TENANT_ID,
  userName: "admin",
  password: "admin123",
  code: "",
  uuid: "",
  clientId: "",
  clientKey: import.meta.env.VITE_APP_CLIENT_KEY,
  grantType: "password"
});
const resCode = reactive<Login.ResCode>({
  captchaEnabled: true,
  img: "",
  uuid: ""
});
const getCode = async () => {
  const res = await codeApi();
  resCode.captchaEnabled = res.captchaEnabled;
  const uuid = res.uuid;
  loginForm.uuid = uuid;
  const clientSecret = import.meta.env.VITE_APP_CLIENT_SECRET;
  const clientId = md5(uuid + clientSecret);
  if (typeof clientId === "string") {
    loginForm.clientId = clientId;
  } else {
    loginForm.clientId = "";
  }
  if (res.img) {
    resCode.img = "data:image/gif;base64," + res.img;
  } else {
    resCode.img = "";
  }
};
// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const res: Login.ResLogin = await loginApi(loginForm);
      userStore.setToken(res.accessToken);
      userStore.setUserInfo(res);
      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      tabsStore.closeMultipleTab();
      keepAliveStore.setKeepAliveName();

      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: res.nickname,
        type: "success",
        duration: 3000
      });
    } catch (e) {
      getCode();
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  getCode();
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
